<!--
 * @description 新建/编辑小组
 * @author dumeng
 * @date 2021/9/17
 -->
<template>
  <div class="group-create-page">
    <div class="page-title">新建/编辑</div>
    <section class="page-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="兴趣小组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入兴趣小组名称" />
        </el-form-item>
        <el-form-item label="logo" prop="groupLogo" required>
          <image-upload
            :key="uploadImg.imagecropperKey"
            v-model="form.groupLogo"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="160"
            :view="uploadImg.view"
            :height="160"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="分类" prop="classifyId">
          <el-select v-model="form.classifyId" placeholder="请选择分类" clearable :style="{width:'100%'}">
            <el-option v-for="(item, index) in classifyOptions" :key="index" :label="item.classifyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设置组长" prop="groupLeader">
          <el-tag v-if="form.groupLeader" closable @close="deleteLeader()">
            {{ form.leaderName }}
          </el-tag>
          <el-button class="button-new-tag" size="small" @click="addLeader">选择组长</el-button>
        </el-form-item>
        <el-form-item label="简介" prop="groupSummary">
          <el-input v-model="form.groupSummary" :rows="6" type="textarea" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="小组可见范围">
          <el-radio-group v-model="form.isVisual">
            <el-radio
              v-for="(item, index) in visualOption"
              :key="index"
              :label="item.dictValue"
            >{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>
    <section class="page-footer">
      <el-button style="padding: 10px 30px;" @click="back">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <!-- 添加管理员弹框  -->
    <add-user
      v-if="dialogFormVisible"
      ref="selectLeader"
      v-loading.fullscreen.lock="fullscreenLoading"
      @userData="userData"
      @cancel="dialogFormVisible = false"
    />
  </div>
</template>

<script>

import { int } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog'
import { getClassifyTree, get, insert, update } from '../api/groupManage'
import AddUser from '../components/user'
export default {
  name: 'XqxzGroupCreate',
  directives: {
    elDragDialog
  },
  components: { AddUser },
  data() {
    return {
      state: 'create',
      classifyOptions: [],
      visualOption: [
        {
          dictName: '不登录也可见',
          dictValue: '0'
        }, {
          dictName: '注册用户可见',
          dictValue: '1'
        }, {
          dictName: '认证用户可见',
          dictValue: '2'
        }, {
          dictName: '小组成员可见',
          dictValue: '3'
        }
      ],
      form: {
        id: '',
        groupName: '',
        groupLogo: '',
        groupSummary: '',
        classifyId: '',
        isVisual: '2',
        groupLeader: '',
        leaderName: '',
        sort: ''
      },
      rules: {
        groupName: [
          { required: true, message: '请输入兴趣小组名称', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        groupLogo: [
          { required: true, message: '请上传logo', trigger: 'change' }
        ],
        groupLeader: [
          { required: true, message: '请选择组长', trigger: 'blur' }
        ],
        classifyId: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        isVisual: [
          { required: true, message: '请选择小组可见范围', trigger: 'change' }
        ],
        groupSummary: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        sort: [
          { required: false, validator: int, trigger: 'blur' }
        ]
      },
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      dialogFormVisible: false,
      fullscreenLoading: false
    }
  },
  created() {
    if (this.$route.query.t) {
      this.state = this.$route.query.t
    }
    this.getClassifyOption()
  },
  methods: {
    /**
     * 获取分类
     */
    getClassifyOption() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'HDFL_XQXZ ' }).then(({ data }) => {
          this.classifyOptions = data.data || []
          resolve()
          if (this.state === 'update') {
            this.getData(this.$route.query.gi)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 添加用户
    addLeader() {
      this.dialogFormVisible = true
    },
    deleteLeader() {
      this.form.groupLeader = ''
      this.form.leaderName = ''
    },
    userData(info) {
      this.form.groupLeader = info.id
      this.form.leaderName = info.userRealname
    },
    back() {
      // this.$router.push({ path: this.$filterPath('groupManage') })
      this.handleCancel()
    },
    handleCancel() {
      this.$router.push({ path: this.$filterPath('groupManage'), query: { gi: this.$route.query.gi, tab: this.$route.query.tab, ci: this.$route.query.ci, gn: this.$route.query.gn }})
    },
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            return new Promise((resolve, reject) => {
              insert(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['deptIds'] = this.form.deptIds && this.form.deptIds.length > 0 ? this.form.deptIds.join(',') : ''
            return new Promise((resolve, reject) => {
              update(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.handleCancel()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(id).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            this.form[key] = data[key]
          }
          this.uploadImg.viewId = data.groupLogo
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .group-create-page {
    background-color: #fff;
    min-height: calc(100vh - 60px);
    max-height: calc(100vh - 60px);
    overflow: hidden;
    .page-title {
      position: relative;
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      background-color: #ffffff;
      border-bottom: 1px solid #e5e5e5;
      font-family: PingFangSC-Medium;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      font-size: 14px;
      &:before {
        content: '';
        position: absolute;
        width: 2px;
        @include bg-color($mainColor);
        top: 13px;
        bottom: 13px;
        left: 15px;
      }
    }
    .page-main {
      position: absolute;
      top: 50px;
      left: 0;
      right: 0;
      bottom: 52px;
      box-sizing: border-box;
      padding: 0 10px;
      overflow: hidden;
      &::-webkit-scrollbar {
        width: 8px; /*对垂直流动条有效*/
        height: 1px; /*对水平流动条有效*/
      }
      /** 滚动条轨道*/
      &::-webkit-scrollbar-track {
        box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
        background-color: white;
        border-radius: 3px;
      }
      /** 滚动条里面小方块*/
      &::-webkit-scrollbar-thumb {
        height: 32px;
        border-radius: 5px;
        box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
        background-color: #eaeaea;
      }
      &:hover {
        overflow: auto;
      }
      .form {
        width: 1000px !important;
        margin: 0 auto;
        .el-select {
          width: 100%;
        }

        .line {
          text-align: center;
        }
      }
    }
    .page-footer {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      text-align: center;
      padding: 10px 0;
      background-color: white;
      box-shadow: 0 -3px 6px #f5f5f5;
    }
  }
</style>
